package lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by lizhenyu on 2019/9/26
 * description
 */
public class FairLock {

    // 设置 true 为公平锁，false 为非公平锁
    private ReentrantLock lock = new ReentrantLock(true);

    public void lock() {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + " 获取到锁");
    }

    public void unLock() {
        lock.unlock();
        System.out.println(Thread.currentThread().getName() + " 释放锁");
    }

    class LockThread extends Thread{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 启动");
            lock();
            unLock();
        }
    }

    public void lockTest() {
        Thread[] tasks = new Thread[10];
        for (int i = 0; i < 10; i++) {
            tasks[i] = new LockThread();
        }
        for (int i = 0; i < 10; i++) {
            tasks[i].start();
        }
    }

    public static void main(String[] args) {
        FairLock fairLock = new FairLock();
        fairLock.lockTest();
    }
}
